﻿using System;
using System.Data.Objects.SqlClient;
using System.Linq;
using System.Web.Mvc;
using CP_SchoolForChildren_v0._1.Controllers.Support;
using CP_SchoolForChildren_v0._1.Models.DataModel;

namespace CP_SchoolForChildren_v0._1.Controllers.BE
{
    public class ArticleManagementController : Controller
    {
        private FunctionController fc = new FunctionController();
        private SFCMessage sfcMessage = new SFCMessage();

        //[Authorize(Roles = "Editor")]
        [Authorize(Roles = "Admin")]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Category()
        {
            return View();
        }

        [Authorize(Roles = "Admin,Editor")]
        [HttpPost]
        public JsonResult ListArticle(string keywords, int jtStartIndex, int jtPageSize, string jtSorting)
        {
            try
            {
                if (keywords == null)
                    keywords = "";
                //Get Data
                int userID = fc.CurrentUserID(User.Identity.Name);
                var role = fc.db.Users.First(u => u.UserID == userID).RoleID;
                 var tmp = from a in fc.db.Articles
                             join c in fc.db.Categories on a.CategoryID equals c.CategoryID
                             join us in fc.db.Users on a.UserID equals  us.UserID
                             where a.Title.Contains(keywords)
                             select new
                                        {
                                            ArticleID = a.ArticleID,
                                            ArticleTitle = a.Title + ";" + SqlFunctions.StringConvert((double)a.ArticleID),
                                            CategoryName = c.CategoryName,
                                            Username = us.UserName,
                                            UserID = us.UserID,
                                            CreatedTime = a.CreatedTime
                                            
                                        };
                var record = tmp;
                if (role == 2)
                    record = tmp.Where(u => u.UserID == userID);
                //Get Totalrow
                var totalrow = record.Count();
                //Paging
                var temp = record.OrderUsingSortExpression(jtSorting).
                    Skip(jtStartIndex).Take(jtPageSize);


                return Json(new { Result = "OK", Records = temp.ToList(), TotalRecordCount = totalrow });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = sfcMessage.ServerError });
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult CreateArticle(Article article)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                                    {
                                        Result = "ERROR",
                                        Message = "Form is not valid! " +
                                                  "Please correct it and try again."
                                    });
                }
                    var record = fc.db.Articles.Add(article);
                    fc.db.SaveChanges();
                    return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult UpdateArticle(Article article)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
                }


                fc.db.Entry(article).State = System.Data.EntityState.Modified;
                var record = fc.db.SaveChanges();
                return Json(new { Result = "OK", Record = record });

            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.ToString() });
            }
        }

        [Authorize(Roles = "Admin,Editor")]
        [HttpPost]
        public JsonResult DeleteArticle(Article article)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new {Result = "ERROR", Message = "Form is not valid! Please correct it and try again."});
                }
                    fc.db.Configuration.ProxyCreationEnabled = false;
                    fc.db.Entry(article).State = System.Data.EntityState.Deleted;
                    var record = fc.db.SaveChanges();
                    return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        #region Category
        [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult ListCategory(string keywords, int jtStartIndex, int jtPageSize, string jtSorting)
        {
            try
            {
                if (keywords == null)
                    keywords = "";
                //Get Data
                var record = from c in fc.db.Categories
                             where c.CategoryName.Contains(keywords)
                             select new
                                        {
                                            CategoryID = c.CategoryID,
                                            CategoryName = c.CategoryName,
                                            ArticleCount = c.Articles.Count
                                        };
                                
                //Get Totalrow
                var totalrow = record.Count();
                //Paging
                var temp = record.OrderUsingSortExpression(jtSorting).
                    Skip(jtStartIndex).Take(jtPageSize);


                return Json(new {Result = "OK", Records = temp.ToList(), TotalRecordCount = totalrow});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult CreateCategory(Category category)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new
                                    {
                                        Result = "ERROR",
                                        Message = "Form is not valid! " +
                                                  "Please correct it and try again."
                                    });
                }
                if (!CheckNewService(category))
                {
                    return Json(new { Result = "ERROR", Message = "Dữ liệu đã tồn tại" });
                }
                var record = fc.db.Categories.Add(category);
                fc.db.SaveChanges();
                return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult UpdateCategory(Category category)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new {Result = "ERROR", Message = "Form is not valid! Please correct it and try again."});
                }
                if (!CheckService(category))
                {
                    return Json(new { Result = "ERROR", Message = "Dữ liệu đã tồn tại" });
                }
                fc.db.Entry(category).State = System.Data.EntityState.Modified;
                var record = fc.db.SaveChanges();
                return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        [Authorize(Roles = "Admin")]
        [HttpPost]
        public JsonResult DeleteCategory(Category category)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new {Result = "ERROR", Message = "Form is not valid! Please correct it and try again."});
                }
                if (CheckServiceFK(category))
                {
                    return Json(new { Result = "ERROR", Message = sfcMessage.ForeginKey });
                }
                fc.db.Entry(category).State = System.Data.EntityState.Deleted;
                var record = fc.db.SaveChanges();
                return Json(new {Result = "OK", Record = record});
            }
            catch (Exception ex)
            {
                return Json(new {Result = "ERROR", Message = ex.ToString()});
            }
        }

        // Delete all row in SchoolService
        [Authorize(Roles = "Admin")]
        public bool CheckServiceFK(Category category)
        {
            var query = from a in fc.db.Articles
                        where a.CategoryID == category.CategoryID
                        select a;
            if (query.Any())
                return true;
            return false;
        }

        // Check dupplicate name
        [Authorize(Roles = "Admin")]
        public bool CheckService(Category category)
        {
            var record = fc.db.Categories.
                Where(c => c.CategoryID != category.CategoryID).
                Where(c => c.CategoryName == category.CategoryName).
                ToList();
            if (record.Any())
                return false;
            return true;
        }

        [Authorize(Roles = "Admin")]
        public bool CheckNewService(Category category)
        {
            var record = fc.db.Categories.
                Where(c => c.CategoryName == category.CategoryName).ToList();
            if (record.Any())
                return false;
            return true;
        }
        #endregion
    }
}